<?php
declare (strict_types = 1);
namespace app\api\controller;

use app\BaseController;
use think\Request;
use think\Exception;
use think\facade\{Log, Db};
use think\exception\ValidateException;

use app\api\validate\CardValidate;

use app\api\model\{Users, Goods, UserCard};

class UserCardController extends BaseController
{
    /**
	 * 次卡列表
	 */
    public function getCardList()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(CardValidate::class)->scene('list')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $userModel  = new Users();
            $goodsModel = new Goods();
            $cardModel  = new UserCard();

            // 获取用户信息
            $userInfo = $userModel->getUserInfo(['id' => $data['user_id']]);

            if(!isset($userInfo['bind_admin_id'])){
                $this->error_back($userInfo);
            }

            $where = [
                'user_id'  => $data['user_id'], 
                'admin_id' => $userInfo['bind_admin_id'], 
                'status'   => $data['status']
            ];

            if(isset($data['type'])){
                $where['goods_type'] = $data['type'];
            }else{
                $where['goods_type'] = 1;
            }

            $list = $cardModel->getList($where, 1, $data['curr'], $data['limit']);

            if($list['code'] != 'ok'){
                $this->error_back($list['msg']);
            }

            $backData = [];

            foreach($list['data'] as $k => $v){
                // 次卡信息
                $goods_info = $goodsModel->getFind(['id' => $v['goods_id']])['data'];

                // 使用期限
                $time = date('Y-m-d H:i:s', $v->getData('create_time') + $goods_info->getData('use_days') * 86400);
                
                $backInfo = [
                    'id'          => $v['id'], 
                    'goods_id'    => $v['goods_id'], 
                    'name'        => $goods_info['title'], 
                    'small_img'   => $goods_info['small_img'],
                    'card_number' => $v['card_number'] . '/' . $v['card_number_all'],
                    'time'        => $goods_info['use_days'] ? '请于' . $time . '前使用' : '永久有效',
                    'status'      => $v->getData('status'),
                ];       

                $backData[] = $backInfo;
            }

            $this->success_back('ok', $backData);
        }
    }

    /**
	 * 次卡核销
	 */
    public function setCard()
    {
        $data = input('post.');

        // 验证数据
        try{
            validate(CardValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }
        
        $cardModel = new UserCard();

        /** 次卡信息 */
        $card_info = $cardModel->getFind(['id' => $data['card_id']])['data'];

        if($card_info->getData('status') == 2){
            $this->error_back('次数已用完');
        }else if($card_info->getData('status') == 3){
            $this->error_back('次卡已过期');
        }

        if($card_info['write_time'] + 1 * 60 > time()){
            $this->error_back('操作太频繁，请1分钟后重试');
        }

        /** 减次数 */
        $flag = $cardModel->where(['id' => $data['card_id']])->dec('card_number', 1)->update();

        if(!$flag){
            $this->error_back('操作失败');
        }

        /** 重新查询次卡信息 */
        $info = $cardModel->getFind(['id' => $data['card_id']])['data'];

        if($info['card_number'] <= 0){
            /** 可用次数为0，改状态 */
            $cardModel->edit(['id' => $data['card_id'], 'status' => 2, 'end_time' => time()]);
        }else{
            $cardModel->edit(['id' => $data['card_id'], 'write_time' => time()]);
        }

        $user_info = Db::name('users')->where(['id' => $info['user_id']])->find();

        /** 一代受益人ID */
        if($user_info['pid'] > 0){
            $fst_pid = $user_info['pid'];
        }else{
            $this->success_back('ok');
        }

        /** 查询次卡商品信息 */
        $goods_info = Db::name('goods')->where(['id' => $info['goods_id']])->find();

        $order_info = Db::name('order')->where(['id' => $info['order_id']])->find();

        /** 实例化消息提醒 */
        $newsController = new NewsController($this->app);

        Db::startTrans(); 
        try {
            /** 店铺ID */
            $admin_id = $info['admin_id'];

            /** 一级分销佣金 */
            $fstMoney = $goods_info['fst_rate'] * $order_info['price'];

            /** 二级分销佣金 */
            $secMoney = $goods_info['sec_rate'] * $order_info['price'];

            if($fstMoney > 0){
                /** 一代受益人用户信息 */
                $userFstInfo = Db::name('users')->where(['id' => $fst_pid])->find();

                /** 一代受益人在当前店铺的资产信息 */
                $userFstShopInfo = Db::name('user_shop')->where(['user_id' => $fst_pid, 'admin_id' => $admin_id])->find();

                 /** 一级分销 */
                if($userFstShopInfo){
                    /** 增加一代受益人在当前店铺的佣金 */
                    $fst_money_flag = Db::name('user_shop')->where(['user_id' => $fst_pid, 'admin_id' => $admin_id])->inc('money', (float)$fstMoney)->update();
                    
                    if($fst_money_flag === false){
                        throw new Exception("更新会员一级佣金失败【" . $fst_pid . "】");
                    }
                    
                    /** 写入财务记录 */
                    $fst_fin_flag = addFin($fst_pid, $admin_id, $info['order_id'], 1, 1, '+' . $fstMoney, '会员一级佣金');

                    if($fst_fin_flag === false){
                        throw new Exception("会员一级佣金记录添加失败【" . $fst_pid . "】");
                    }

                    /** 公众号消息提醒 */
                    $newsController->news_money($fst_pid, $info['user_id'], $info['goods_id'], $fstMoney);

                    /** 二级分销 */
                    if($userFstInfo['pid'] > 0 && $secMoney > 0){
                        /** 二代受益人在当前店铺的资产信息 */
                        $userSecShopInfo = Db::name('user_shop')->where(['user_id' => $userFstInfo['pid'], 'admin_id' => $admin_id])->find();

                        if($userSecShopInfo){
                            /** 增加二代受益人在当前店铺的佣金 */
                            $sec_money_flag = Db::name('user_shop')->where(['user_id' => $userFstInfo['pid'], 'admin_id' => $admin_id])->inc('money', (float)$secMoney)->update();

                            if($sec_money_flag === false){
                                throw new Exception("更新会员二级佣金失败【" . $userFstInfo['pid'] . "】");
                            }

                            /** 写入财务记录 */
                            $fst_fin_flag = addFin($userFstInfo['pid'], $admin_id, $info['order_id'], 1, 1, '+' . $secMoney, '会员二级佣金');

                            if($fst_fin_flag === false){
                                throw new Exception("会员二级佣金记录添加失败【" . $userFstInfo['pid'] . "】");
                            }

                            /** 公众号消息提醒 */
                            $newsController->news_money($userFstInfo['pid'], $info['user_id'], $info['goods_id'], $secMoney);
                        }
                    }
                }
            }

            Db::commit();
        }catch(Exception $e){
            Db::rollback();
            Log::write($e->getMessage());
            $this->error_back($e->getMessage());
        }

        /** 公众号消息提醒 */
        $newsController->news_consume($info['user_id'], $info['admin_id'], $data['card_id'], 1);
        $newsController->news_service($info['to_user_id'], $info['user_id'], $info['goods_id']);
        $this->success_back('ok');
    }
}